<template>
  <div ref="chart"></div>
</template>

<script setup>
import { ref, watch, reactive, onMounted } from 'vue'
import * as echarts from 'echarts'
import { get_score } from '../../../../api/api';

const props = defineProps({
  selectedStudentId: {
    type: Number,
    required: false,
    default: 1,
  },
});

// 监听 selectedStudentId 的变化并调用 fetchData
watch(() => props.selectedStudentId, (newValue) => {
  // console.log('Selected Student ID changed:', newValue);
  if (newValue) {
    fetchData(newValue); // 传递 newValue 到 fetchData
  }
});

// 获取 token
const getToken = () => {
  return localStorage.getItem('pz_token');
};

// 请求数据并更新状态
const fetchData = async (StudentID) => {
  // console.log('StudentID=', StudentID);
  try {
    const token = getToken();

    if (!token) {
      console.error('未找到 Token');
      return;
    }

    if (!StudentID) {
      console.error('无效的 StudentID:', StudentID);
      return;
    }

    // 设置请求头
    const headers = {
      'Authorization': `JWT ${token}`, // 将 token 作为 Bearer Token 传递
    };

    // console.log('Request headers:', headers);  // 打印请求头，确保包含 token

    const response = await get_score(StudentID, headers);
    // console.log('response:', response);

    const gradeData = response.data.data.data; // 这里获取实际的返回数据

    // console.log('gradeData:', gradeData);  // 打印 classData 的结构

    // 将 gradeData 映射到 trafficWay
    if (gradeData) {
      trafficWay[0].value = gradeData.excellent || 0;
      trafficWay[1].value = gradeData.good || 0;
      trafficWay[2].value = gradeData.qualified || 0;
      trafficWay[3].value = gradeData.unqualified || 0;
    }

    // 清空 data 数组
    data.length = 0;

    for (let i = 0; i < trafficWay.length; i++) {
      data.push(
        {
          value: trafficWay[i].value,
          name: trafficWay[i].name,
          itemStyle: {
            borderWidth: 5,
            shadowBlur: 20,
            borderColor: color[i],
            shadowColor: color[i]
          }
        },
        {
          value: 2,
          name: '',
          itemStyle: {
            label: { show: false },
            labelLine: { show: false },
            color: 'rgba(0, 0, 0, 0)',
            borderColor: 'rgba(0, 0, 0, 0)',
            borderWidth: 0
          }
        }
      );
    }
    // console.log('Updated trafficWay:', trafficWay);
    // console.log(data);
    const myChart = echarts.init(chart.value)
    myChart.setOption(option)
    window.addEventListener('resize', () => {
      myChart.resize()
    })
  } catch (error) {
    console.error('获取数据失败:', error);
  }
};

const trafficWay = [
  { name: "优秀", value: 0 },
  { name: "良好", value: 0 },
  { name: "合格", value: 0 },
  { name: "不合格", value: 0 }
];

// console.log('trafficWay:', trafficWay);
const chart = ref();
// 配置 ECharts 的选项
const img = '';

const data = [
  {
    value: 0,
    name: "优秀",
    itemStyle: {
      borderWidth: 5,
      shadowBlur: 20,
      borderColor: "#00ffff",
      shadowColor: "#00ffff"
    }
  },
  {
    value: 2,
    name: "",
    itemStyle: {
      label: {
        show: false
      },
      labelLine: {
        show: false
      },
      color: "rgba(0, 0, 0, 0)",
      borderColor: "rgba(0, 0, 0, 0)",
      borderWidth: 0
    }
  },
  {
    value: 0,
    name: "良好",
    itemStyle: {
      borderWidth: 5,
      shadowBlur: 20,
      borderColor: "#00cfff",
      shadowColor: "#00cfff"
    }
  },
  {
    value: 2,
    name: "",
    itemStyle: {
      label: {
        show: false
      },
      labelLine: {
        show: false
      },
      color: "rgba(0, 0, 0, 0)",
      borderColor: "rgba(0, 0, 0, 0)",
      borderWidth: 0
    }
  },
  {
    value: 0,
    name: "合格",
    itemStyle: {
      borderWidth: 5,
      shadowBlur: 20,
      borderColor: "#006ced",
      shadowColor: "#006ced"
    }
  },
  {
    value: 2,
    name: "",
    itemStyle: {
      label: {
        show: false
      },
      labelLine: {
        show: false
      },
      color: "rgba(0, 0, 0, 0)",
      borderColor: "rgba(0, 0, 0, 0)",
      borderWidth: 0
    }
  },
  {
    value: 0,
    name: "不合格",
    itemStyle: {
      borderWidth: 5,
      shadowBlur: 20,
      borderColor: "#ffe000",
      shadowColor: "#ffe000"
    }
  },
  {
    value: 2,
    name: "",
    itemStyle: {
      label: {
        show: false
      },
      labelLine: {
        show: false
      },
      color: "rgba(0, 0, 0, 0)",
      borderColor: "rgba(0, 0, 0, 0)",
      borderWidth: 0
    }
  }
];
const color = ['#00ffff', '#00cfff', '#006ced', '#ffe000', '#ffa800', '#ff5b00', '#ff3000'];

const seriesOption = [
  {
    name: '',
    type: 'pie',
    clockwise: false,
    radius: [70, 74],
    emphasis: { scale: false },
    label: {
      show: true,
      position: 'outside',
      color: '#ddd',
      formatter(params) {
        const total = trafficWay.reduce((sum, item) => sum + item.value, 0);
        const percent = ((params.value / total) * 100).toFixed(0);
        return params.name ? `成绩等级：${params.name}\n占百分比：${percent}%` : '';
      }
    },
    labelLine: {
      length: 18,
      length2: 10,
      color: '#00ffff'
    },
    data: data
  }
];

const option = reactive({
  backgroundColor: '',
  color: color,
  title: {
    text: '成绩分布',
    top: '43%',
    left: '49%',
    textAlign: "center",
    textStyle: {
      color: '#fff',
      fontSize: 20,
      fontWeight: '400'
    }
  },
  graphic: {
    elements: [
      {
        type: "image",
        z: 3,
        style: { image: img, width: 100, height: 100 },
        left: 'center',
        top: 'center'
      }
    ]
  },
  tooltip: { show: true },
  legend: {
    icon: "circle",
    orient: 'vertical',
    data: ['优秀', '良好', '合格', '不合格'],
    // ['优秀', '良好', '合格', '不合格']
    left: 0,
    bottom: 0,
    textStyle: {
      color: "#fff",
      fontSize: 10,
      fontWeight: '400'
    },
    itemGap: 10,
    itemWidth: 10,
    itemHeight: 10
  },
  series: seriesOption
});


onMounted(() => {
  const myChart = echarts.init(chart.value)
  myChart.setOption(option)
  window.addEventListener('resize', () => {
    myChart.resize()
  })
})

</script>

<style lang="less" scoped></style>


const img =
'';
